import cheerio from 'cheerio';
import path from "path";
import fs from "fs";
interface Analyzer {
  analyze: (html: string, filePath: string) => string;
}
interface Course {
  title: string;
  imgUrl: string;
}
interface CourseInfoResult {
  time: number;
  data: Course[];
}
interface JsonContent {
    [propName:number]: Course[];
}
/**
 * 分析器 单例模式
 */
export default class WillesAnalyzer implements Analyzer {
  private static instance: WillesAnalyzer;
  static getInstance() {
    if (!WillesAnalyzer.instance) {
      WillesAnalyzer.instance = new WillesAnalyzer();
    }
    return WillesAnalyzer.instance;
  }
  private getCourseInfo(html: string) {
    const $ = cheerio.load(html);
    const courseItem = $(".content li");
    const courseInfos: Course[] = [];
    courseItem.map((index:any, el: any) => {
      const title = $(el).find(".album-title").text();
      const imgUrl = $(el).find("img").attr("src") || '';
      courseInfos.push({ title, imgUrl });
    });
    console.log(courseInfos)
    return {
      time: new Date().getTime(),
      data: courseInfos,
    };
  }
  private generateJsonContent(courseInfo: CourseInfoResult, filePath: string) {
      let jsonContent: JsonContent = {}
      if (fs.existsSync(filePath)) {
          let content = fs.readFileSync(filePath, 'utf-8') || '{}'
          jsonContent = JSON.parse(content)
      }
    jsonContent[courseInfo.time] = courseInfo.data
    return jsonContent
  }
  public analyze(html: string, filePath: string) {
     const content = this.getCourseInfo(html) 
     const data = this.generateJsonContent(content, filePath)
    return JSON.stringify(data);
  }
}
